package wetalk.software.bupt.com.wetalk.view.activity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jyt.message.Message;
import com.jyt.util.MySerializable;

import org.json.JSONException;
import org.json.JSONObject;

import wetalk.software.bupt.com.wetalk.DB.WeTalkDB;
import wetalk.software.bupt.com.wetalk.R;
import wetalk.software.bupt.com.wetalk.application.UserManager;
import wetalk.software.bupt.com.wetalk.communicate.AndroidClientService;
import wetalk.software.bupt.com.wetalk.listener.PushListener;
import wetalk.software.bupt.com.wetalk.model.po.User;
import wetalk.software.bupt.com.wetalk.view.dialog.CustomDialog;
import wetalk.software.bupt.com.wetalk.widget.ClearEditText;

/**
 * 添加好友的界面，只有一个搜索框
 */
public class AddFriendsActivity extends BaseActivity {
    private static final String TAG="AddFriendsActivity";

    private IntentFilter intentFilter;
    private UserInfoReceiver userInfoReceiver;

    private AndroidClientService.SendBinder sendBinder;

    private ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            sendBinder= (AndroidClientService.SendBinder) iBinder;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
        }
    };

    ClearEditText et;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_friends);
        initTitle();
        Button bt=(Button)findViewById(R.id.bt_search);

        Intent bindIntent = new Intent(this, AndroidClientService.class);
        this.bindService(bindIntent, connection, BIND_AUTO_CREATE);

        et=(ClearEditText)findViewById(R.id.et_friends_search);

        intentFilter=new IntentFilter("return_fetch_userInfo");
        userInfoReceiver=new UserInfoReceiver();
        registerReceiver(userInfoReceiver,intentFilter);

        bt.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                User user;
                String content=et.getText().toString();
                if(TextUtils.isEmpty(content)){
                    Toast.makeText(AddFriendsActivity.this, "您输入的内容为空", Toast.LENGTH_SHORT).show();
                } else {
                    user=WeTalkDB.create(AddFriendsActivity.this).queryFri(content);
                    if(user!=null){
                        UserInfoActivity.actionStart(AddFriendsActivity.this,user,"look");
                    } else{
                        searchUser(content);
                        CustomDialog.getDialog(AddFriendsActivity.this,"正在查找...").show();
                    }
                }
            }
        });

    }

    private void initTitle(){
        RelativeLayout rvRight=(RelativeLayout)findViewById(R.id.rv_img_right);
        rvRight.setVisibility(View.GONE);
        TextView txt=(TextView)findViewById(R.id.txt_title);
        txt.setText("添加朋友");
        RelativeLayout rvLeft=(RelativeLayout)findViewById(R.id.rv_img_back);
        rvLeft.setVisibility(View.VISIBLE);
        rvLeft.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }



    private void searchUser(String number)  {
        final String targetId = "sys_userinfo";
        final String userId= UserManager.getInstance(AddFriendsActivity.this).getCurrentUser().getUserID();
        final JSONObject json=new JSONObject();
        try {
            json.put("id",number);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {
                byte[] bs;
                bs = MySerializable.object_bytes(json.toString());
                Message msg = new Message(userId,targetId,"fetchUserInfo",bs);
                sendBinder.sendMessage(msg);
            }
        });
        thread.start();
        Log.d(TAG,"发送查找好友的请求"+json.toString());
    }

    class UserInfoReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            CustomDialog.getDialog(AddFriendsActivity.this,"正在查找...").close();
            String content=intent.getStringExtra("fetchUserInfo");
            Log.d(TAG,"onReceive-->"+content);
            try {
                if(content==null||content.equals("{}")){
                    Toast.makeText(context, "用户不存在", Toast.LENGTH_SHORT).show();
                }else{
                    JSONObject jsonObject=new JSONObject(content);
                    User user=new User();
                    user.setUserId((String)jsonObject.get("id"));
                    user.setUserName((String)jsonObject.get("name"));
                    user.setEmail((String)jsonObject.get("email"));
                    user.setDepartment((String)jsonObject.get("department"));
                    user.setPhone((String)jsonObject.get("phone"));
                    user.setAvatar((String)jsonObject.get("avatar"));
                    UserInfoActivity.actionStart(AddFriendsActivity.this, user, "add");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(userInfoReceiver);
        unbindService(connection);
    }
}
